<template>
	<el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" node-key="id" ref="treeComponent"
		:draggable="true" @node-drop="nodeDrop" :show-checkbox="checked"></el-tree>
</template>

<script>
	import {
		sendComponentEventRequest
	} from '@/utils/requestUtils.js';
	import utils from '@/utils/utils.js';
	export default {
		name: "TreeComponent",
		props: ["componentModel"],
		data() {
			return {
				data: [],
				defaultProps: {
					children: 'children',
					label: 'name'
				},
				selectedId: "",
				checked: false,
			};
		},
		inject: ['children'],
		mounted() {
			this.children.push(this);
			this.checked = this.componentModel.checked;
		},beforeUnmount() {
			utils.removeArrayElement(this.children,this);
		},
		methods: {
			handleNodeClick(data) {
				this.selectedId = data.id;
				if (this.componentModel.itemClickEvent == true) {
					sendComponentEventRequest(this, "itemClickEvent", {});
				}
			},
			setProp(prop) {
				var datamodel = prop["data"];
				if (datamodel != undefined && datamodel != null) {
					this.data = [datamodel];
				}
				var selectedValue = prop["selectedvalue"];
				if (selectedValue != undefined) {
					this.setSelectedValue(selectedValue)
				}
			},
			setSelectedValue(value) {
				if (this.componentModel.checked === true) {
					if (value != null && value.length > 0) {
						this.$refs.treeComponent.setCheckedKeys(value, true);
					}
					return;
				}
				var type = typeof value;
				var id;
				if (type == "number") {
					id = value + "";
				} else if (type == "object") {
					id = value.id;
				} else if (type == "string") {
					id = value;
				}
				this.selectedId = id;
			},
			updateTreeNode(para) {
				var node = this.$refs.treeComponent.getNode(para.id);
				node.data.name = para.name;
			},
			addTreeNode(para) {
				this.$refs.treeComponent.append(para, this.selectedId);
			},
			removeTreeNode(para) {
				var node = this.$refs.treeComponent.getNode(para.id);
				this.$refs.treeComponent.remove(node);
			},
			getState() {
				var data = {};
				if (this.componentModel.checked === true) {
					var checkedKeys = this.$refs.treeComponent.getCheckedKeys();
					var halfCheckedKeys = this.$refs.treeComponent.getHalfCheckedKeys();
					var selectedValue = checkedKeys.join(",");
					if (halfCheckedKeys.length > 0) {
						selectedValue += "," + halfCheckedKeys.join(",");
					}
					data[this.componentModel.id] = selectedValue;
				} else {
					data[this.componentModel.id] = this.selectedId;
				}
				return data;
			},
			nodeDrop(sourceNode, targetNode, moveType) {
				var data={};
				data[this.componentModel.id + "_sourceId"]=sourceNode.data.id;
				data[this.componentModel.id + "_targetId"]=targetNode.data.id;
				data[this.componentModel.id + "_moveType"]=moveType;
				sendComponentEventRequest(this, "moveNodeEvent", data);
			}
		}
	};
</script>

<style>
</style>
